<template>
  <div class="min-h-screen bg-white flex justify-center">
    <div class="w-full max-w-[800px] p-4 pb-20">
      <!-- 顶部导航 -->
      <div class="nav-header">
        <div class="nav-header-content">
          <div class="back-button" @click="goBack">
            <van-icon name="arrow-left" size="20" />
          </div>
          <div class="header-title">中奖记录</div>
          <div class="header-actions"></div>
        </div>
      </div>

      <!-- 记录列表 -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="mt-16">
        <div class="records-container">
          <!-- 空状态 -->
          <div v-if="loading && !records.length" class="empty-state">
            <van-loading type="spinner" size="24px" />
            <p class="empty-text">加载中...</p>
          </div>
          
          <div v-else-if="records.length === 0" class="empty-state">
            <van-icon name="gift-o" size="48" class="empty-icon" />
            <p class="empty-text">暂无中奖记录</p>
            <p class="empty-subtext">快去参与抽奖，赢取丰厚奖品吧！</p>
            <van-button 
              type="primary" 
              class="mt-4"
              @click="navigateTo('/lucky_draw')"
            >
              立即抽奖
            </van-button>
          </div>
          
          <!-- 记录列表 -->
          <div v-else class="records-list">
            <div 
              v-for="record in records" 
              :key="record.id"
              class="record-item"
            >
              <div class="record-left">
                <div 
                  class="prize-icon" 
                  :style="{ backgroundColor: record.prizeColor }"
                >
                  <van-icon name="gift-o" class="text-white" v-if="record.prizeName === '谢谢参与'" />
                </div>
              </div>
              <div class="record-content">
                <div class="record-title">{{ record.prizeName }}</div>
                <div class="record-time">{{ formatDate(record.createTime) }}</div>
              </div>
              <div class="record-right">
                <div class="record-status" :class="record.status === 'claimed' ? 'claimed' : 'unclaimed'">
                  {{ record.status === 'claimed' ? '已领取' : '未领取' }}
                </div>
                <div class="record-action" v-if="record.status !== 'claimed'">
                  <van-button 
                    size="small" 
                    type="primary" 
                    @click="claimPrize(record)"
                  >
                    领取
                  </van-button>
                </div>
              </div>
            </div>
            
            <!-- 加载更多 -->
            <div class="load-more">
              <van-loading v-if="loading" type="spinner" size="20" class="loading-icon" />
              <template v-else>
                <div v-if="hasMore" @click="loadMore" class="load-more-btn">
                  点击加载更多
                </div>
                <div v-else class="no-more">
                  没有更多记录了
                </div>
              </template>
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { getPrizeRecords, claimPrize as claimPrizeApi } from '@/api/lucky_draw'

const router = useRouter()
const records = ref([])
const loading = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const hasMore = ref(true)

// 获取中奖记录
const fetchRecords = async (isRefresh = false) => {
  loading.value = true
  try {
    const page = isRefresh ? 1 : currentPage.value
    
    const res = await getPrizeRecords({
      page,
      pageSize: pageSize.value
    })
    
    if (res.code === 0 && res.data) {
      if (isRefresh) {
        records.value = res.data.list
      } else {
        records.value = [...records.value, ...res.data.list]
      }
      
      total.value = res.data.total
      
      // 判断是否还有更多数据
      hasMore.value = page * pageSize.value < total.value
      
      // 更新当前页码
      currentPage.value = page
    } else {
      showToast(res.message || '获取记录失败')
    }
  } catch (error) {
    console.error('获取中奖记录失败:', error)
    showToast('获取记录失败，请稍后重试')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  currentPage.value = 1
  fetchRecords(true)
}

// 加载更多
const loadMore = () => {
  if (loading.value || !hasMore.value) return
  
  currentPage.value += 1
  fetchRecords()
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 领取奖品
const claimPrize = async (record) => {
  try {
    showLoadingToast({
      message: '领取中...',
      forbidClick: true,
    })
    
    const res = await claimPrizeApi({
      prizeId: record.prizeId,
      recordId: record.id
    })
    
    if (res.code === 0 && res.data && res.data.success) {
      showToast(res.data.message || '奖品已发放到您的账户')
      // 更新记录状态
      record.status = 'claimed'
      record.claimTime = new Date().toISOString()
    } else {
      showToast(res.message || '领取失败，请稍后重试')
    }
    
    showLoadingToast().close()
  } catch (error) {
    console.error('领取奖品失败:', error)
    showToast('领取失败，请稍后重试')
    showLoadingToast().close()
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 导航到指定页面
const navigateTo = (path) => {
  router.push(path)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRecords(true)
})
</script>

<style scoped>
/* 基础样式 */
.min-h-screen {
  min-height: 100vh;
}

.bg-white {
  background-color: #ffffff;
}

.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

.w-full {
  width: 100%;
}

.max-w-\[800px\] {
  max-width: 800px;
}

.p-4 {
  padding: 1rem;
}

.pb-20 {
  padding-bottom: 5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.mt-16 {
  margin-top: 4rem;
}

/* 导航头部样式 */
.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  z-index: 100;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  max-width: 800px;
  margin: 0 auto;
}

.nav-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  height: 56px;
}

.header-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  text-align: center;
  margin: 0 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.back-button {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
}

.back-button:active {
  transform: scale(0.95);
  background-color: #f5f5f5;
}

.header-actions {
  width: 36px;
}

/* 记录列表样式 */
.records-container {
  padding-top: 1rem;
}

.records-list {
  margin-bottom: 1rem;
}

.record-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: white;
  transition: background-color 0.2s ease;
}

.record-item:last-child {
  border-bottom: none;
}

.record-item:hover {
  background-color: #f9f9f9;
}

.record-left {
  margin-right: 16px;
}

.prize-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.record-content {
  flex: 1;
}

.record-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.record-time {
  font-size: 13px;
  color: #999;
}

.record-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.record-status {
  font-size: 14px;
  margin-bottom: 8px;
}

.record-status.claimed {
  color: #2563eb;
}

.record-status.unclaimed {
  color: #f59e0b;
}

.record-action {
  margin-top: 4px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  text-align: center;
}

.empty-icon {
  color: #ddd;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
}

.empty-subtext {
  font-size: 14px;
  color: #999;
  margin-bottom: 16px;
}

/* 文本样式 */
.text-white {
  color: white;
}

/* 加载更多样式 */
.load-more {
  padding: 16px 0;
  text-align: center;
}

.load-more-btn {
  display: inline-block;
  color: #2563eb;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #f0f7ff;
  cursor: pointer;
  transition: all 0.2s ease;
}

.load-more-btn:active {
  background-color: #e0f0ff;
  transform: scale(0.98);
}

.no-more {
  color: #999;
  font-size: 14px;
  padding: 8px 0;
}

.loading-icon {
  margin: 0 auto;
}
</style>
